<?php
global $framework;
require_once("$framework/session.php");

/**
 * Helpers to manage Cart from session.
 * @author frederic
 *
 */
class CartHelpers{
	
	/**
	 * retrieve Cart from html session.
	 * @return an arry formated as : array(''count'=>99, 'list'=>array()
	 */
	public function get(){
		$cart=Session::get("cart");
		__debug(__CLASS__."::getCart() => cart=".print_r($cart,true));
		if(empty($cart)){
			$cart = array(	'count'	=> 0,
				'list'	=> array());
			Session::set("cart",$cart);	
		}else{
			$cart=Session::get("cart");
		}
		return $cart;
	}
	
	/**
	 * Store cart into user html session.
	 * @param $cart cart content. array formated as array('count'=>99, 'list'=>array(array('product'=>$product,'qty'=>1),...)
	 * @return unknown_type
	 */
	public function set($cart){
		Session::set("cart",$cart);
	}
	
	/**
	 * Add a <strong>$product</strong> product to the cart with a <strong>$qty</strong> quantity.
	 * @param $product the product object to be added to cart
	 * @param $qty the quantity of this object.
	 */
	public function addToCart($product, $qty=1){
		__debug(__CLASS__."::addToCart() product=".$product->name."qty=".$qty);
		$cart = self::get();
		if(!empty($cart['list'][$product->product_id])&&getType($product)=="Product"){
			$cart['list'][$product->product_id]['qty']+=$qty;
		}else{
			if(empty($cart['list'])) $cart['list'] = array();
			$cart['list'][$product->product_id] = array('product'=>serialize($product), 'qty'=>$qty);
			$cart['count']++;
		}
		__debug(__CLASS__."::addToCart() product[".$product->product_id."]='".$product->name."' added to cart");
		self::set($cart);
	}
	
	/**
	 * Remove an article from the cart.
	 * @param $product
	 * @param $qty
	 * @return unknown_type
	 */
	public function removeFromCart($product, $qty=1){
		__debug(__CLASS__."::removeFromCart() product=".$product->name."qty=".$qty);
		$cart = self::get();
		if($cart['list'][$product->product_id]['qty']-$qty>1){
			$cart['list'][$product->product_id]['qty']-=$qty;
		}else{
			$cart['list'][$product->product_id]=0;
			$cart['count']--;
		}
		__debug(__CLASS__."::removeFromCart() product[".$product->product_id."]='".$product->name."' added to cart");
		self::set($cart);
			}
}
?>